package com.paishen.peiniwan.module.login;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.paishen.common.dialog.LoadingDialog;
import com.paishen.common.util.BaseUtil;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.AuthCode;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.paishen.peiniwan.frame.widget.InputEditLayout;
import com.squareup.okhttp.Request;

public class RegisterAuthActivity extends BaseActivity {
    private String authTitle;
    public static final String EXTRA_AUTH_TITLE = "extra_auth_title";

    private InputEditLayout layEditPhone, layEditAuth;
    private TextView txAuth;
    private static final int DEFAULT_COUNTDOWN = 60;
    private int countdownTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        authTitle = getIntent().getStringExtra(EXTRA_AUTH_TITLE);
        setContentView(R.layout.activity_register_auth);

        BaseUtil.setStatusBarDarkMode(true, this);

        findViewById(R.id.lay_container).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseUtil.hideSoftInputFromWindowAlways(RegisterAuthActivity.this);
            }
        });

        TextView txTitle = (TextView) findViewById(R.id.tx_title);
        txTitle.setText(authTitle);

        layEditPhone = (InputEditLayout) findViewById(R.id.lay_edit_phone);
        layEditPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
        layEditAuth = (InputEditLayout) findViewById(R.id.lay_edit_auth);
        layEditAuth.setInputType(InputType.TYPE_CLASS_NUMBER);

        findViewById(R.id.tx_next).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkAuthInfo(true)) {
                    requestCheckValidCode();
                }
            }
        });

        txAuth = (TextView) findViewById(R.id.tx_auth);
        txAuth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (layEditPhone.getText().length() != 11) {
                    BaseUtil.showToast(R.string.register_fail_phone_1);
                    return;
                }
                requestSendValidCode();
            }
        });

        View imgBack = findViewById(R.id.img_back);
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) imgBack.getLayoutParams();
        int fixHeight = BaseUtil.dip2px(4);
        lp.setMargins(0, fixHeight + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);
        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseUtil.hideSoftInputFromWindowAlways(this);
    }

    private boolean checkAuthInfo(boolean remind) {
        boolean result = true;
        if (TextUtils.isEmpty(layEditPhone.getText())) {
            result = false;
            if (remind) BaseUtil.showToast(R.string.login_input_username);
        }
        return result;
    }

    /**
     * 验证码短信获取重置倒计时 默认为60秒 {@link RegisterAuthActivity#DEFAULT_COUNTDOWN}
     */
    private void refreshValidCountdown() {
        txAuth.setText(getString(R.string.register_retry_valicode, countdownTime));
        txAuth.postDelayed(new Runnable() {
            @Override
            public void run() {
                countdownTime--;
                if (countdownTime <= 0) {
                    txAuth.setText(R.string.register_get_valicode);
                    txAuth.setEnabled(true);
                } else {
                    refreshValidCountdown();
                }
            }
        }, 1000);
    }

    private void requestSendValidCode() {
        String phone = layEditPhone.getText().toString();
        String type = "undefined";

            type = "forget";

        txAuth.setText(R.string.register_get_valicode_1);
        txAuth.setEnabled(false);
        PnwHttpManager.User.sendValidCode(TAG, phone, type, new PnwOkCallbackAdapter<HttpRespData<AuthCode>>() {
            @Override
            public void onResponse(HttpRespData<AuthCode> response, boolean fresh) {
                super.onResponse(response, fresh);
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    countdownTime = DEFAULT_COUNTDOWN;
                    refreshValidCountdown();
                    // respAuthCode = response.data.code;
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE){
                    BaseUtil.showToast(response.errmsg);
                    txAuth.setText(R.string.register_get_valicode);
                    txAuth.setEnabled(true);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                txAuth.setText(R.string.register_get_valicode);
                txAuth.setEnabled(true);
            }
        });
    }


    private void requestCheckValidCode() {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(this).create();
        dlgLoading.show();

        final String phone = layEditPhone.getText().toString();
        final String vcode = layEditAuth.getText().toString();
        PnwHttpManager.User.checkValidCode(TAG, phone, vcode, new PnwOkCallbackAdapter<HttpRespData<AuthCode>>() {
            @Override
            public void onResponse(HttpRespData<AuthCode> response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    Intent intent = new Intent(RegisterAuthActivity.this, RegisterSetPwdActivity.class);
                    intent.putExtra(RegisterSetPwdActivity.EXTRA_AUTH_CODE, vcode);
                    intent.putExtra(RegisterCompleteActivity.EXTRA_PHONE, phone);
                    startActivity(intent);
                    finish();
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE){
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }
}
